package camid.distribution.interceptor;

import java.util.Iterator;
import java.util.List;

import camid.distribution.protocol.MethodRequestMessage;
import camid.distribution.protocol.MethodResponseMessage;

public class InterceptorChain {
	
	private final MethodRequestMessage requestMessage;
	
	private final Iterator<InvocationInterceptor> interceptors;
	
	private final InvocationEvaluator evaluator;

	public InterceptorChain(MethodRequestMessage requestMessage,
			List<InvocationInterceptor> interceptors, InvocationEvaluator evaluator) {
		super();
		this.requestMessage = requestMessage;
		this.interceptors = interceptors.iterator();
		this.evaluator = evaluator;
	}
	
	public MethodResponseMessage proceed() throws Exception {
		MethodResponseMessage responseMessage = null;
		if (interceptors.hasNext()) {
			InvocationInterceptor interceptor = interceptors.next();
			responseMessage = interceptor.intercept(this);
		} else {
			responseMessage = this.evaluator.evaluate(requestMessage);
		}
		return responseMessage;
	}

	public MethodRequestMessage getRequestMessage() {
		return requestMessage;
	}

}
